import React from 'react';
import axios from 'axios';
import { Toast } from 'antd-mobile';
import { isEmptyObj } from '@/util/tools';
import path from '@/config/path';

const isCanRedirect = ({location}, goUrl = '') => {
    return goUrl !== location.pathname;
};

/**
 * Nat decorator
 * @param Main Component
 * @return Component Class
 */
export default (Main) => {
    return class extends React.Component{
        componentDidMount(){

            if(!this.props.history){
                throw new Error('please add @withRouter on this decorator before.');
            }

            const IS_DENUG = /debug/.test(window.location.href);
            const props = this.props;
            const HISTORY = props.history;
            const LOAD = "loading";
            const SHOWTIME = 0;
            const QUEUE = {};
            let flg = 0; 

            // showLog
            const showLog = (data) => {
                IS_DENUG && console.log(data)
            }

            // interceptor request
            axios.interceptors.request.use((req)=>{
                showLog(req);
                req.id = flg++;
                QUEUE[req.id] = "";
                Toast.loading(LOAD, SHOWTIME);
                return req;
            });

            // interceptor response
            axios.interceptors.response.use((res) => {
                showLog(res);
        
                delete QUEUE[res.config.id];
                
                if(isEmptyObj(QUEUE)){
                    Toast.hide();
                }
        
                // show server msg
                const RD = res.data,
                      SCODE = RD.code,
                      SMSG = RD.msg;

                setTimeout(() => {
                    1004 === SCODE && this.props.clearLogin();
                });

                1004 !== SCODE && (200 !== SCODE ? SMSG && Toast.fail(SMSG, 1) : SMSG && Toast.success(SMSG, 1));
                
                return res;
            }, (error) => {
                const res = error.response;
                const status = res.status;
                
                showLog(res);
 
                Toast.fail('登录超时或者未登录', 1, () => {
                    switch(status){
                        case 403:
                        case 401: isCanRedirect(props, path[30001]) && HISTORY.push(path[30001]);break; // 网络异常跳转到专门的404 403页面这里就不实现了
                        default: isCanRedirect(props, path[30001]) && HISTORY.push(path[30001]);break;
                    }
                });

                Toast.hide();
                return Promise.reject(error);
            });
        }
        render(){
            return <Main {...this.props} />
        }
    }
}